import random
import string
import tkinter as tk

def show():
    listbox1.delete(0,tk.END)
    listbox2.delete(0,tk.END)
    listbox1.insert(tk.END, *stu_choose)
    for key,value in name_sub.items():
        listbox2.insert(tk.END, '{} --- {}'.format(str(key),value))

def counts():
    listbox3.delete(0,tk.END)
    for i in sorted(enumerate(percent_sub), key = lambda x:x[1], reverse = True):
        listbox3.insert(tk.END, '{} --- {} --- {}'.format(str(i[0]+1), name_sub[i[0]+1],i[1]))
        
def num_single():
    return random.choice('1234567')

def num_multiple():
    num_choose=''
    for i in range(3):
        num_choose += num_single()
    return num_choose

stu_choose = [num_multiple() for i in range(100)] # 随机生成学生选课序号
num_effective = len(stu_choose) # 有效人数
name_sub= dict(zip(range(1,8),('物理化学生物政治历史地理技术'[i:i+2] for i in range(0,14,2)))) # 学科序号表
count_sub = dict.fromkeys(range(1,8), 0) # 每门课有效被选次数
percent_sub = [] # 每门课选课率

# 统计每门课有效被选次数及有效人数
for i in stu_choose:
    j = 0
    while j != len(i):
        count_sub[int(i[j])] += 1
        if i[j] in i[j + 1:]:
            num_effective -= 1
            for z in range(j + 1):
                count_sub[int(i[z])] -= 1
            break
        j += 1

# 计算每门课选课率
for i in range(1,8):
    percent_sub.append('{:.2%}'.format(count_sub[i] / num_effective))
    
# 建立窗口
win = tk.Tk()
win.title('选课统计')
win.resizable(0, 0)

# 建立组件
lb1 = tk.Label(win, text = '选课组合')
lb2 = tk.Label(win, text = '编号    学科')
lb3 = tk.Label(win, text = '编号    学科    选课率')
y_scrollbar = tk.Scrollbar(win)
y_scrollbar.grid(row = 1, column = 1, sticky = tk.N + tk.S + tk.W)
listbox1 = tk.Listbox(win, justify = 'center', yscrollcommand = y_scrollbar.set)
listbox2 = tk.Listbox(win, justify = 'center')
listbox3 = tk.Listbox(win, justify = 'center')
cmd1 = tk.Button(win, text = '显示', command = show)
cmd2 = tk.Button(win, text = '统计', command = counts)

# 组件布局
lb1.grid(row = 0)
lb2.grid(row = 0, column = 1)
lb3.grid(row = 0, column = 3)
listbox1.grid(row = 1, sticky = tk.N + tk.S + tk.E + tk.W)
y_scrollbar['command'] = listbox1.yview
listbox2.grid(row = 1, column = 1, padx = 20)
listbox3.grid(row = 1, column = 3, padx = 20)
cmd1.grid(row = 1, column = 2)
cmd2.grid(row = 2, column = 2)

# 接收窗口事件
win.mainloop()
